package cn.crism.chatme.controller;

import cn.crism.chatme.bo.UserInfoBO;
import cn.crism.chatme.enums.SearchFriendsStatusEnum;
import cn.crism.chatme.pojo.UserInfo;
import cn.crism.chatme.service.UserService;
import cn.crism.chatme.utils.*;
import cn.crism.chatme.vo.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * @CreateDate: 2018/12/25 9:18 AM
 * @Description:
 * @Author: Crism
 */

@RestController
@RequestMapping("u")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FastDFSClient fastDFSClient;

    /* 注册或者登陆 */
    @PostMapping("/registerOrLogin")
    public JSONResult registerOrLogin(@RequestBody UserInfo user) {

        String userName = user.getUserName().replaceAll("\\s*", "");
        String passWord = user.getPassword().replaceAll("\\s*", "");

        // 0. 判断用户名和密码不能为空
        if (StringUtils.length(userName) < 5 || StringUtils.length(userName)>12) {
            return JSONResult.errorMsg("用户名长度5-12位！");
        }
        if (StringUtils.length(passWord) < 8 || StringUtils.length(passWord) > 20) {
            return JSONResult.errorMsg("密码长度8-20位！");
        }

        // 1. 判断用户名是否存在，如果存在就登录，如果不存在则注册
        boolean usernameIsExist = userService.userNameIsExist(userName);

        UserInfo userResult = null;
        if (usernameIsExist) {
            // 1.1 登录
            userResult = userService.userInfoIsExist(user.getUserName(), MD5Util.md5(user.getPassword()));

            if (userResult == null) {
                return JSONResult.errorMsg("用户名或密码不正确...");
            }
        } else {
            // 1.2 注册
            user.setNickName(user.getUserName());
            user.setFaceImg("");
            user.setFaceImgBig("");
            user.setPassword(MD5Util.md5(user.getPassword()));
            userResult = userService.saveUser(user);
        }

        UserInfoVO userVO = new UserInfoVO();
        BeanUtils.copyProperties(userResult, userVO);

        return JSONResult.ok(userVO);
    }


    @PostMapping("/uploadFaceImgBase64")
    public JSONResult uploadFaceImgBase64(@RequestBody UserInfoBO userBO) throws Exception {

        String base64Data = userBO.getFaceData();
        String faceTempPath = "/root/chatMe/" + userBO.getUserId() + "userfaceimg.png";
        FileUtils.base64ToFile(faceTempPath, base64Data);

        /* 上传文件到fastdfs */
//        MultipartFile faceImg = FileUtils.fileToMultipart(faceTempPath);
//        String imgUrl = fastDFSClient.uploadBase64(faceImg);
        String path = QiniuCloudUtil.uploadQNImg(faceTempPath, userBO.getUserId() + "userfaceimg.png");
        FileUtils.deleteFile(faceTempPath);
//        String stmp = "_80x80.";
//        String arr[] = imgUrl.split("\\.");
//        String sImgUrl = arr[0] + stmp + arr[1];

        UserInfo user = new UserInfo();
        user.setUserId(userBO.getUserId());
        user.setFaceImg(path);
        user.setFaceImgBig(path);

        UserInfoVO userVO = new UserInfoVO();
        BeanUtils.copyProperties(userService.updateUserInfo(user), userVO);
        return JSONResult.ok(userVO);
    }


    @PostMapping("/setNickName")
    public JSONResult setNickName(@RequestBody UserInfoBO userBO) {

        String nickName = userBO.getNickName().replaceAll("\\s*", "");
        if (StringUtils.length(nickName)<5 || StringUtils.length(nickName)>12){
            return JSONResult.errorMsg("昵称度为5-12位！");
        }
        if (StringUtils.isBlank(userBO.getUserId())) {
            return JSONResult.errorMsg("参数不能为空！");
        }
        UserInfo user = new UserInfo();
        user.setUserId(userBO.getUserId());
        user.setNickName(userBO.getNickName());
        UserInfoVO userVO = new UserInfoVO();
        BeanUtils.copyProperties(userService.updateUserInfo(user), userVO);
        return JSONResult.ok(userVO);

    }


    @PostMapping("/searchUser")
    public JSONResult searchUser(@RequestParam("myUserId") String myUserId,
                                 @RequestParam("friendUserName") String friendUserName) {

        friendUserName = friendUserName.replaceAll("\\s*", "");
        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUserName)) {
            return JSONResult.errorMsg("参数不能为空！");
        }
        /*
         * 搜索的用户不存在 返回[不存在]
         * 搜索的用户是自己 返回[不能添加自己]
         * 搜索的用户已添加 返回[该用户已经是你的好友]
         * */
        System.out.println(myUserId);
        System.out.println(friendUserName);
        Integer status = userService.preconditionSearchFriend(myUserId, friendUserName);
        if (status != SearchFriendsStatusEnum.SUCCESS.status) {
            return JSONResult.errorMsg(SearchFriendsStatusEnum.getMsgByKey(status));
        }
        UserInfo user = userService.queryUserInfoByUserName(friendUserName);
        UserInfoVO userVO = new UserInfoVO();
        BeanUtils.copyProperties(userService.updateUserInfo(user), userVO);
        return JSONResult.ok(userVO);
    }

    @PostMapping("/sendFriendRequest")
    public JSONResult sendFriendRequest(@RequestParam("myUserId") String myUserId,
                                        @RequestParam("friendUserName") String friendUserName) {

        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUserName)) {
            return JSONResult.errorMsg("参数不能为空！");
        }
        /*
         * 搜索的用户不存在 返回[不存在]
         * 搜索的用户是自己 返回[不能添加自己]
         * 搜索的用户已添加 返回[该用户已经是你的好友]
         * */
        Integer status = userService.preconditionSearchFriend(myUserId, friendUserName);
        if (status != SearchFriendsStatusEnum.SUCCESS.status) {
            return JSONResult.errorMsg(SearchFriendsStatusEnum.getMsgByKey(status));
        }
        userService.sendFriendRequest(myUserId, friendUserName);
        return JSONResult.ok();
    }


}
